package com.huihe.framework.config.serializer;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.Filter;
import com.huihe.common.constant.Constants;
import io.micrometer.common.lang.NonNullApi;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Redis使用FastJson序列化
 */
@NonNullApi
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {

    /**
     * 序列化和反序列化的编码
     */
    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(Constants.JSON_WHITELIST_STR);

    /**
     * 要把Byte[]反序列化的目标类
     */
    private final Class<T> clazz;

    public FastJson2JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    /**
     * 将输入的对象序列化为字节数组
     * @param value 要序列化的对象
     * @return 序列化的byte[]数组
     */
    @Override
    public byte[] serialize(T value) throws SerializationException {
        return JSON.toJSONString(value, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    /**
     * 将取出来的对象反序列化为对象
     * @param bytes byte[]数组
     * @return 反序列化对象
     */
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        String str = new String(bytes,DEFAULT_CHARSET);
        //AUTO_TYPE_FILTER:该值用来限定那些类可以被自动识别转换
        return JSON.parseObject(str,clazz,AUTO_TYPE_FILTER);
    }
}
